import Component from 'utils/js/jquery-component';
import createClass from 'utils/js/create-class';
import locals from './index.css';
import html from './index.html';
import loadResources from 'utils/js/loadResources';

export default createClass(Component, {
  __name__: 'Example',
  locals: locals,

  __init__: function (el) {
    this.$wrap = this.$(el || document.body)
    this.$html = this.$(this.rh(html));
    this.$html.appendTo(this.$wrap);
    this.$progress = this.$html.find(this.rs('.progress'));
    this.$colorBar = this.$html.find(this.rs('.color'));
    this.$imgBar = this.$html.find(this.rs('.imgBar'));
  },

  fadeIn: function () {
    this.$html.fadeIn();
  },

  show: function () {
    this.$html.show();
  },

  fadeOut: function () {
    this.$html.fadeOut();
  },

  hide: function () {
    this.$html.hide();
  },

  moveProgressBar: function (p) {
    var percent = p + '%';
    this.$progress.text(percent);
    this.$colorBar.add(this.$imgBar).css('transform', 'translate(' + percent + ')');
  },

  load: function (obj) {
    var me = this;
    var leastShowTime = 2000; // 最少显示时间（毫秒）
    var hideTime = Date.now() + leastShowTime;

    me.$html.show();

    return new Promise(function (resolve, reject) {
      loadResources(
        obj,
        me.moveProgressBar.bind(me)
      ).then(function (d) {
        setTimeout(function () {
          me.$html.fadeOut();
          resolve(d);
        }, hideTime - Date.now());
      }).catch(reject);
    });
  }
});
